<template>
  <el-container class="layout-ltb">
    <el-container>
      <el-header height="114">
        <el-form
          ref="queryFormRef"
          :model="queryParams"
          size="small"
          label-position="right"
          class="search-form mt-[20px]"
        >
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="等级" prop="Level">
                <el-select placeholder="请选择" v-model="queryParams.Level">
                  <el-option label="高" value="1" />
                  <el-option label="中" value="2" />
                  <el-option label="低" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="隐患状态" prop="Status">
                <el-select
                  placeholder="请选择按区域/路线巡检"
                  v-model="queryParams.Status"
                >
                  <el-option label="待处理" :value="1 * 1" />
                  <el-option label="进行中" :value="2 * 1" />
                  <el-option label="已完成" :value="3 * 1" />
                  <el-option label="暂不处理" :value="0 * 1" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="发现时间" prop="InspDestId">
                <el-date-picker
                  v-model="dateRange1"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  append-to-body="false"
                  :clearable="false"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="处理时间">
                <el-date-picker
                  v-model="dateRange2"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  append-to-body="false"
                  :clearable="false"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="部门" prop="HandleDepartmentId">
                <el-select
                  placeholder="请选择"
                  v-model="queryParams.HandleDepartmentId"
                  @change="f_ChangeDep"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                    v-for="item in depData"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="上报人员" prop="CreateUserId">
                <el-select
                  placeholder="请选择"
                  v-model="queryParams.CreateUserId"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                    v-for="item in operatorData"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="处理人员" prop="HandleUserId">
                <el-select
                  placeholder="请选择"
                  v-model="queryParams.HandleUserId"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                    v-for="item in operatorAllData"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="搜索" prop="KeyWords">
                <el-input
                  v-model="queryParams.KeyWords"
                  placeholder="请输入隐患名称/描述/工单编号"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="10" style="text-align: right">
              <el-button
                @click="f_HandleSearch"
                type="primary"
                class="btn-search"
                size="small"
              >
                <i-ep-search class="mr-[2px] text-size-[11px] v-bottom" />搜索
              </el-button>
              <el-button
                @click="f_HandleReset"
                type="warning"
                class="btn-reset"
              >
                <i-ep-refresh class="mr-[2px] text-size-[11px] v-bottom" />重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="6" />
        </el-row>
      </el-header>
      <el-main>
        <div>
          <el-table
            v-if="tableData.length"
            :data="tableData"
            border
            :height="tableHeight"
            header-row-class-name="table-header"
            size="small"
          >
            <el-table-column
              type="index"
              width="60"
              label="序号"
              align="center"
            />
            <!-- <el-table-column
              prop="planSetName"
              label="巡检计划名称"
              align="center"
            />
            <el-table-column prop="planSetType" label="计划类型" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.planSetType == 1" type="primary"
                  >日计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 2" type="success"
                  >周计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 3" type="info"
                  >月计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 4" type="warning"
                  >季计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 5" type="danger"
                  >年计划</el-tag
                >
              </template>
            </el-table-column> -->
            <el-table-column
              prop="dangerName"
              label="隐患名称"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="dangerContent"
              label="隐患描述"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="address"
              label="地址"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="level"
              label="隐患等级"
              align="center"
              show-overflow-tooltip
            >
              <template #default="scope">
                <el-tag v-if="scope.row.level == 1" type="danger">高</el-tag>
                <el-tag v-if="scope.row.level == 2" type="warning">中</el-tag>
                <el-tag v-if="scope.row.level == 3" type="success">低</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="隐患状态" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.status == null" type="primary"
                  >--</el-tag
                >
                <el-tag v-if="scope.row.status == 0" type="success"
                  >暂不处理</el-tag
                >
                <el-tag v-if="scope.row.status == 1" type="info">待处理</el-tag>
                <el-tag v-if="scope.row.status == 2" type="warning"
                  >处理中</el-tag
                >
                <el-tag v-if="scope.row.status == 3" type="danger"
                  >已处理</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="handleDepartmentName"
              label="巡检部门"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="creater"
              label="上报人员"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="createrTel"
              label="联系电话"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="reportTime"
              label="发现隐患时间"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="handleTime"
              label="处理隐患时间"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="handleDuration"
              label="处理时长"
              align="center"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.handleDuration }}h
              </template>
            </el-table-column>
            <el-table-column
              prop="handleMethod"
              label="处理措施"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="handler"
              label="处理人员"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="handlerTel"
              label="联系电话"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="workOrderId"
              label="工单编号"
              align="center"
              show-overflow-tooltip
            />
            <el-table-column
              prop="remark"
              label="备注"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="操作"
              align="center"
              width="200"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  @click="f_OpenDialog(scope.row)"
                  type="primary"
                  size="small"
                  link
                  ><i-ep-view
                    class="mr-[2px] text-size-[11px] v-bottom"
                  />详情</el-button
                >

                <el-button
                  v-if="scope.row.status != 2 && scope.row.status != 3"
                  @click="f_OpenHandleDialog(scope.row)"
                  type="primary"
                  size="small"
                  link
                  ><i-ep-view
                    class="mr-[2px] text-size-[11px] v-bottom"
                  />去处理</el-button
                >

                <el-button
                  v-if="scope.row.status == 1"
                  @click="f_HandleDel(scope.row)"
                  type="danger"
                  size="small"
                  link
                  ><i-ep-delete
                    class="mr-[2px] text-size-[11px] v-bottom"
                  />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <noneData :noneShow="!tableData.length" :height="tableHeight" />
          <pagination
            size="small"
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize"
            @pagination="f_HandelQuery"
          />
        </div>
      </el-main>
    </el-container>

    <!-- 弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      title="隐患详情"
      size="1400"
      append-to-body
      @close="f_CloseDialog"
      class="bg-[#f5f5f5!important]"
      destroy-on-close
    >
      <edit_drawer :form="form" @close="f_CloseDialog" />
    </el-drawer>

    <!-- 处理隐患 -->
    <el-dialog
      v-model="dialogHandle.visible"
      title="处理隐患"
      width="500px"
      @close="f_CloseDialog(false)"
    >
      <div class="p-[25px]">
        <el-form
          :inline="true"
          size="default"
          label-width="100"
          label-position="left"
        >
          <div>
            <el-form-item label="是否处理" prop="status">
              <el-radio-group
                v-model="handleForm.status"
                @change="f_ChangeHandleStatus"
              >
                <el-radio :value="0">暂不处理</el-radio>
                <el-radio :value="1">立即处理</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div>
            <el-form-item
              v-if="handleForm.status"
              label="选择部门"
              prop="handleDepartmentId"
            >
              <el-select
                placeholder="请选择"
                v-model="handleForm.handleDepartmentId"
                @change="f_ChangeHandleDep"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                  v-for="item in depData"
                />
              </el-select>
            </el-form-item>
          </div>

          <div>
            <el-form-item
              v-if="handleForm.status"
              label="选择处理人"
              prop="handleUserId"
            >
              <el-select placeholder="请选择" v-model="handleForm.handleUserId">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                  v-for="item in operatorHandleData"
                />
              </el-select>
            </el-form-item>
          </div>

          <div>
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                autosize
                placeholder="请输入内容"
                v-model="handleForm.remark"
                :rows="2"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer pb-[15px] mt-[-20px] pr-[15px]">
          <el-button type="primary" @click="f_HandleSubmit">确 定</el-button>
          <el-button @click="f_CloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
defineOptions({
  name: "Inspection",
  inheritAttrs: false,
});
import moment from "moment";
import { find } from "lodash";
import GisPolygonInfoAPI from "@/api/GisPolygonInfoAPI";
import TaskSetAPI from "@/api/TaskSetAPI";
import DangerAPI from "@/api/DangerAPI";
import PlanAPI from "@/api/PlanAPI";
import edit_drawer from "./detail.vue";
let tableHeight = ref(0);
// 弹窗对象
const dialog = reactive({
  visible: false,
  title: "",
});
const dialogHandle = reactive({
  visible: false,
});
const dateRange1 = ref("");
const dateRange2 = ref("");
const operatorAllData = ref([]);
const queryFormRef = ref(ElForm);
const depData = ref([]);
const operatorData = ref([]);
const operatorHandleData = ref([]);
const loading = ref(false);
const total = ref(0);
const tableData = ref([]);
const taskData = ref([]);
const polygonData = ref([]);
const form = ref({
  planSetId: 0,
  planSetName: "",
  taskSetId: undefined,
  planSetType: 0,
  planStartTime: new Date(),
  planEndTime: new Date(),
  isAvoidHoliday: true,
  remark: "",
  planDate: "",
  taskSetCycle: "",
});

const handleForm = ref({
  dangerId: null,
  status: 0,
  handleDepartmentId: undefined,
  handleUserId: undefined,
  remark: "",
});

const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  PlanSetType: undefined,
  TaskSetType: undefined,
  InspDestId: undefined,
  InspDepartmentId: undefined,
  InspUserId: undefined,
  KeyWords: undefined,
});

const operator = ref({
  operatorId: "",
  departmentName: "",
  departmentId: "",
  operatorName: "",
});

// 查询当前登录人信息
function f_HandelQueryOperat() {
  TaskSetAPI.api_query_userinfo().then(({ data, succeeded }) => {
    if (succeeded) {
      operator.value.operatorId = data.operatorId;
      operator.value.departmentId = data.departments[0].departmentId;
      operator.value.departmentName = data.departments[0].departmentName;
      operator.value.operatorName = data.operatorName;
    }
  });
}

// 获取分公司下所有操作员
function f_HandelQueryAllOperat() {
  TaskSetAPI.api_query_operators({}).then(({ data, succeeded }) => {
    if (succeeded) {
      operatorAllData.value = data;
    }
  });
}

// 重置
function f_HandleReset() {
  queryFormRef.value.resetFields();
  dateRange1.value = "";
  dateRange2.value = "";
  operatorData.value = [];
  // f_HandleSearch();
}

// 删除
function f_HandleDel(data: any) {
  ElMessageBox.confirm("确认删除数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      DangerAPI.api_del(data.dangerId).then(({ data, errors, succeeded }) => {
        if (succeeded) {
          ElMessage.success("删除成功！");
          f_HandelQuery();
        } else {
          f_HandelQuery();
          ElMessage.error(errors);
        }
        loading.value = false;
      });
    })
    .catch(() => ElMessage.info("已取消删除!"));
}

// 打开弹框
function f_OpenHandleDialog(data) {
  handleForm.value.dangerId = data.dangerId;
  handleForm.value.status = 0;
  handleForm.value.handleDepartmentId = undefined;
  handleForm.value.handleUserId = undefined;
  handleForm.value.remark = "";

  dialogHandle.visible = true;
}

// 打开弹窗
function f_OpenDialog(data: any) {
  form.value = data;
  dialog.visible = true;
}

// 搜索
function f_HandleSearch() {
  queryParams.pageIndex = 1;
  f_HandelQuery();
}

// 查询
function f_HandelQuery() {
  loading.value = true;
  if (dateRange1.value && dateRange1.value.length) {
    queryParams.ReportStartTime = moment(dateRange1.value[0]).format(
      "yyyy-MM-DD 00:00:00"
    );
    queryParams.ReportEndTime = moment(dateRange1.value[1]).format(
      "yyyy-MM-DD 23:59:59"
    );
  } else {
    delete queryParams.ReportStartTime;
    delete queryParams.ReportEndTime;
  }

  if (dateRange2.value && dateRange2.value.length) {
    queryParams.HandleStartTime = moment(dateRange2.value[0]).format(
      "yyyy-MM-DD 00:00:00"
    );
    queryParams.HandleEndTime = moment(dateRange2.value[1]).format(
      "yyyy-MM-DD 23:59:59"
    );
  } else {
    delete queryParams.HandleStartTime;
    delete queryParams.HandleEndTime;
  }
  DangerAPI.api_query(queryParams).then(({ data, succeeded }) => {
    if (succeeded) {
      tableData.value = data.items;
      total.value = data.totalCount;
    }
  });
}

// 查询 任务
function f_HandelQueryTask() {
  let params = {
    pageIndex: 1,
    pageSize: 100,
  };
  TaskSetAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      taskData.value = data.items;
    }
  });
}

// 处理 提交数据
function f_HandleSubmit() {
  if (
    handleForm.value.status &&
    (!handleForm.value.handleDepartmentId || !handleForm.value.handleUserId)
  ) {
    ElMessage.error("请选择处理部门或处理人！");
    return;
  }
  if (!handleForm.value.status) {
    handleForm.value.handleDepartmentName = operator.value.departmentName;
    handleForm.value.handler = operator.value.operatorName;
    handleForm.value.handleDepartmentId = operator.value.departmentId;
    handleForm.value.handleUserId = operator.value.operatorId;
  } else {
    handleForm.value.handler = find(operatorHandleData.value, {
      id: handleForm.value.handleUserId,
    }).name;
    handleForm.value.handleDepartmentName = find(depData.value, {
      id: handleForm.value.handleDepartmentId,
    }).name;
  }
  DangerAPI.api_handle(handleForm.value).then(({ data, succeeded }) => {
    if (succeeded) {
      ElMessage.success("提交成功！");
      f_CloseDialog();
    }
  });
}

// 查询 区域
function f_HandelQueryPolygon() {
  let params = {
    pageSize: 100,
    pageIndex: 1,
  };
  GisPolygonInfoAPI.api_query_geo(params).then(({ data, succeeded }) => {
    if (succeeded) {
      polygonData.value = data.items;
    }
  });
}

// 查询 部门
function f_HandelQueryDep() {
  TaskSetAPI.api_query_dep().then(({ data, succeeded }) => {
    if (succeeded) {
      depData.value = data;
    }
  });
}

// 部门 change
function f_ChangeDep() {
  operatorData.value = [];
  queryParams.CreateUserId = undefined;
  let params = {
    DepartmentId: queryParams.HandleDepartmentId,
  };
  TaskSetAPI.api_query_operators(params).then(({ data, succeeded }) => {
    if (succeeded) {
      operatorData.value = data;
    }
  });
}

// 部门 change
function f_ChangeHandleDep() {
  handleForm.value.handleUserId = undefined;
  let params = {
    DepartmentId: handleForm.value.handleDepartmentId,
  };
  TaskSetAPI.api_query_operators(params).then(({ data, succeeded }) => {
    if (succeeded) {
      operatorHandleData.value = data;
    }
  });
}

// 关闭弹框
function f_CloseDialog() {
  dialog.visible = false;
  dialogHandle.visible = false;
  queryParams.pageIndex = 1;
  f_HandelQuery();
}

// 是否处理 change
function f_ChangeHandleStatus() {
  operatorHandleData.value = [];
  handleForm.value.handleUserId = undefined;
  handleForm.value.handleDepartmentId = undefined;
}

window.onresize = () => {
  return (() => {
    tableHeight.value = window.innerHeight - 320;
  })();
};

onMounted(() => {
  f_HandelQuery();
  f_HandelQueryTask();
  f_HandelQueryDep();
  f_HandelQueryPolygon();
  f_HandelQueryOperat();
  f_HandelQueryAllOperat();
  tableHeight.value = window.innerHeight - 320;
});
</script>
<style scoped lang="scss">
.mydrawer {
  background: red !important;
}

:deep .el-form--inline .el-form-item {
  width: 100%;
}

:deep textarea {
  height: 100px !important;
}
</style>
